<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="角色名称" prop="roleName" align="center" />
      <el-table-column label="角色编码" prop="roleCode" align="center" />
      <el-table-column label="角色介绍" prop="roleDetail" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleSiteScope(scope.row)"
          >站点权限
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色介绍" prop="roleDetail">
          <el-input v-model="form.roleDetail" placeholder="请输入角色介绍" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            ref="menu"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
            :check-strictly="!menuCheckStrictly"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色站点权限对话框 -->
    <el-dialog title="站点权限" :visible.sync="openDataScope" width="500px" append-to-body>
      <el-form v-loading="siteLoading" :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据权限">
          <el-tabs v-model="activeName" tab-position="left">
            <el-tab-pane v-for="i in POLLUTE_TYPE" :key="i.type" :label="i.name" :name="i.alias">
              <el-checkbox v-model="siteExpand[activeName]" @change="handleCheckedTreeExpand($event, 'site',activeName)">展开/折叠</el-checkbox>
              <el-checkbox v-model="siteNodeAll[activeName]" @change="handleCheckedTreeNodeAll($event, 'site',activeName)">全选/全不选</el-checkbox>
              <el-tree
                :ref="i.alias"
                class="tree-border"
                :data="siteOptions[i.alias]"
                show-checkbox
                node-key="SUBID"
                empty-text="加载中，请稍后"
                :props="siteProps"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSiteScope">确 定</el-button>
        <el-button @click="cancelSiteScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { POLLUTE_TYPE } from '@/utils/zhhbConstant'
import pick from 'lodash.pick'
export default {
  name: 'Role',
  data() {
    return {
      siteLoading: false,
      POLLUTE_TYPE,
      activeName: 'KQZ',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（站点权限）
      openDataScope: false,
      // 菜单列表
      menuOptions: [],
      // 站点列表
      siteOptions: {
        KQZ: [],
        YC: [],
        FS: [],
        FQ: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: false,
      siteExpand: {
        KQZ: false,
        YC: false,
        FS: false,
        FQ: false
      },
      siteNodeAll: {
        KQZ: false,
        YC: false,
        FS: false,
        FQ: false
      },
      // 表单参数
      form: {
        id: undefined,
        roleName: undefined, // 角色名称
        roleCode: undefined, // 角色编码
        roleDetail: undefined, // 角色介绍
        menuIds: [],
        subStationIds: []
      },
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      siteProps: {
        children: 'children',
        label: 'SUBNAME'
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '角色编码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true
      this.$http.get('/role/list').then(response => {
        this.roleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      const params = { roleId: 0 }
      this.$http.get('/menu/list', params).then(response => {
        this.menuOptions = this.handleTree(response.data)
      })
    },
    getAllSite() {
      this.$http.get('/position/getMenu').then(res => {
        const data = res.data
        data.forEach(value => {
          switch (value.type) {
            case 1:
              this.siteOptions.KQZ = this.handleTreeByType(value.data, 'STCODE', 'STNAME', 'SUBID', 'SUBNAME')
              break
            case 3:
              this.siteOptions.YC = this.handleTreeByType(value.data, 'STCODE', 'STNAME', 'SUBID', 'SUBNAME')
              break
            case 5:
              this.siteOptions.FS = this.handleTreeByType(value.data, 'STCODE', 'STNAME', 'SUBID', 'SUBNAME')
              break
            case 6:
              this.siteOptions.FQ = this.handleTreeByType(value.data, 'STCODE', 'STNAME', 'SUBID', 'SUBNAME')
              break
          }
        })
      })
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getHalfCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 所有站点节点数据
    getSiteAllCheckedKeys() {
      const checkedNodes = [...this.$refs.KQZ[0].getCheckedNodes(), ...this.$refs.YC[0].getCheckedNodes(), ...this.$refs.FS[0].getCheckedNodes(), ...this.$refs.FQ[0].getCheckedNodes()]
      const array = []
      checkedNodes.forEach(value => {
        if (!value.children) {
          array.push(value.SUBID)
        }
      })
      return array
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      if (this.$refs.KQZ && this.$refs.KQZ[0] !== undefined) {
        this.$refs.KQZ[0].setCheckedKeys([])
      }
      if (this.$refs.YC && this.$refs.YC[0] !== undefined) {
        this.$refs.YC[0].setCheckedKeys([])
      }
      if (this.$refs.FS && this.$refs.FS[0] !== undefined) {
        this.$refs.FS[0].setCheckedKeys([])
      }
      if (this.$refs.FQ && this.$refs.FQ[0] !== undefined) {
        this.$refs.FQ[0].setCheckedKeys([])
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.menuCheckStrictly = false
      this.siteExpand = {
        KQZ: false,
        YC: false,
        FS: false,
        FQ: false
      }
      this.siteNodeAll = {
        KQZ: false,
        YC: false,
        FS: false,
        FQ: false
      }
      this.form = {
        id: undefined,
        roleName: undefined, // 角色名称
        roleCode: undefined, // 角色编码
        roleDetail: undefined, // 角色介绍
        menuIds: [],
        subStationIds: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getMenuTreeselect()
      this.open = true
      this.title = '添加角色'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      this.getMenuTreeselect()
      this.$http.get('/role/info', { entityId: row.id }).then(response => {
        const menuIds = response.data.menuIds
        this.form = response.data
        this.open = true
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(menuIds)
        })
        this.title = '修改角色'
      })
    },
    handleSiteScope(row) {
      this.reset()
      this.getAllSite()
      // subStationId
      this.$http.get('/role/info', { entityId: row.id }).then(response => {
        const subStationIds = response.data.subStationIds
        this.form = response.data
        this.openDataScope = true
        this.$nextTick(() => {
          if (subStationIds) {
            this.$refs.KQZ[0].setCheckedKeys(subStationIds)
            this.$refs.YC[0].setCheckedKeys(subStationIds)
            this.$refs.FS[0].setCheckedKeys(subStationIds)
            this.$refs.FQ[0].setCheckedKeys(subStationIds)
          }
        })
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            const params = pick(this.form, ['id', 'roleName', 'roleCode', 'roleDetail', 'menuIds'])
            this.$http.post('/role/modify', params).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            this.form.menuIds = this.getMenuAllCheckedKeys()
            const params = pick(this.form, ['id', 'roleName', 'roleCode', 'roleDetail', 'menuIds'])
            this.$http.post('/role/add', params).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除该角色?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.$http.post('/role/delete', { entityId: row.id })
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type, siteType) {
      if (type === 'menu') {
        const treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else {
        const treeList = this.siteOptions[siteType]
        for (let i = 0; i < treeList.length; i++) {
          this.$refs[siteType][0].store.nodesMap[treeList[i].SUBID].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type, siteType) {
      if (type === 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else {
        this.$refs[siteType][0].setCheckedNodes(value ? this.siteOptions[siteType] : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type === 'menu') {
        this.menuCheckStrictly = value
      }
    },
    /** 提交按钮（站点权限） */
    submitSiteScope: function() {
      if (this.form.id !== undefined) {
        this.form.subStationIds = this.getSiteAllCheckedKeys()
        const params = {
          id: this.form.id,
          subStationIds: this.form.subStationIds
        }
        this.siteLoading = true
        this.$http.post('/role/modify', params).then(response => {
          if (response.code === 200) {
            this.siteLoading = false
            this.msgSuccess('修改成功')
            this.openDataScope = false
            this.getList()
          }
        })
      }
    },
    // 取消按钮（数据权限）
    cancelSiteScope() {
      this.openDataScope = false
      this.reset()
    }
  }
}
</script>
<style scoped>
  .tree-border {
    margin-top: 5px;
    border: 1px solid #e5e6e7;
    background: #fff none;
    border-radius: 4px;
  }
</style>
